package com.software.levelupandroid.loginAndRegistration.model;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.utils.TokenUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.io.IOException;
import java.util.Map;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description 登录注册的Model
 * @Author LiangYaJie
 * @CreateTime 2024年04月22日 15:51:13
 */
public class MainModel implements IModel {
    private Context context;
    private String loginServerPath;
    private Response response;
    private OkHttpClient okHttpClient;

    public MainModel(Context context) {
        this.context = context;
    }
    @Override
    public void login(final String email, String password, final CallBack callBack){

        okHttpClient = new OkHttpClient();
        loginServerPath = context.getString(R.string.loginServerPath);
        System.out.println(loginServerPath);
        RequestBody requestBody = new FormBody.Builder()
                .add("email", email)
                .add("password", password)
                .build();
        Request request = new Request.Builder()
                .url(loginServerPath)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);

        new Thread(){

            @Override
            public void run(){
                try {

                    response = call.execute();
                    String responseContent = response.body().string();
                    System.out.println(responseContent);

                    Gson gson = new Gson();
                    Result<Map> result = gson.fromJson(responseContent, Result.class);
                    Map data = result.getData();
                    if(result.getCode().equals("200")){
                        String userDetails = gson.toJson(data.get("userDetails"));
                        User user = gson.fromJson(userDetails, User.class);

                        TokenUtil.saveToken((String) data.get("serverToken"),context);
                        UserUtil.saveUser(user,context);
                        callBack.onSuccess(user);
                    }else {
                        Log.e("login", result.getMessage());
                        callBack.onFailure("登录失败");
                    }
                }catch (IOException e){
                    Log.e("login", e.getMessage());
                    callBack.onFailure("登录失败");
                }
            }
        }.start();
    }


}
